package com.rt.code.generator.handler;

import com.rt.code.generator.freemarker.MpGeneratorEnums;
import com.rt.code.generator.freemarker.MpGeneratorSimple;
import com.rt.code.generator.freemarker.dto.GenerateDto;
import com.rt.code.generator.freemarker.exec.FreemarkerGen;
import com.rt.easyjava.common.utils.others.StringUtils;
import com.rt.tmpt.dto.Result;
import com.rt.tmpt.service.IMenuService;
import com.rt.code.generator.freemarker.MpGeneratorComplex;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

@Scope("prototype")
@ApiIgnore
@Controller
@RequestMapping("/admin123/mpgenerator")
public class MpGeneratorAction {

    @Resource
    IMenuService menuService;
    @Resource
    MpGeneratorSimple mpGeneratorSimple;
    @Resource
    MpGeneratorComplex mpGeneratorComplex;
    @Resource
    MpGeneratorEnums mpGeneratorEnums;
    @Resource
    private FreemarkerGen freemarkerGen;

    private ReentrantLock lock = new ReentrantLock();

    /**
     * 模板生成二级菜单
     * genType:
         All(0, "生成所有"),
         Vue(1, "前端"),
         ServiceAll(2, "后端所有"),
         ServiceTmpt(3, "后端通用模板部分"),
         ServiceMyself(4, "后端自定义部分") ;
     * @return
     */
    @RequestMapping(value = "/template2menu")
    @ResponseBody
    public Result template2menu(GenerateDto generateDto, String _userId, HttpServletResponse response){

        String temptTableId = generateDto.getTemptTableId();
        String menu1Id = generateDto.getMenu1Id();
        String menu2Name = generateDto.getMenu2Name();
        String pageType = generateDto.getPageType();
        String keyRandom = generateDto.getKeyRandom();
        boolean downloadZip = generateDto.isDownloadZip();

        Result result = new Result();
        try {
            Map<String,Object> mapParam = new HashMap<String, Object>();
            mapParam.put("_templateTableId",Long.parseLong(temptTableId));
            mapParam.put("menuIdParent",Long.parseLong(menu1Id));
            mapParam.put("menuName",menu2Name);
            mapParam.put("userId",_userId);
            mapParam.put("pageType","pageType");
            mapParam.put("moduleName",generateDto.getModuleName());
            mapParam.put("domainName",generateDto.getDomainName());
            mapParam.put("stripPrefix",generateDto.getStripPrefix());

            // 生成相应菜单
            if (pageType.equals("datagrid")) {
                result = menuService.template2menu(mapParam);
            } else if (pageType.equals("datagrid-sourcecode")) {
                result = menuService.template2menuSourceCode(mapParam);
            }
            // 菜单生成失败了，就停止生成源码了
            /*if(!result.isSuccess()) {
                return result;
            }*/

            if(StringUtils.isNull(keyRandom)){
                if (downloadZip) {
                    return null;
                }else {
                    result.fault("error:操作失败：keyRandom="+keyRandom);
                }
            }
            //生成源码
            if(pageType.equals("datagrid-sourcecode")){
                try {
                    lock.lock();
                    if ("1".equals(generateDto.getCodeType().toString())) {
                        mpGeneratorSimple.execute(generateDto, response);
                    }else{
                        mpGeneratorComplex.execute(generateDto, response);
                    }
                    if (downloadZip) {
                        return null;
                    }else {
                        return result.success();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    if (downloadZip) {
                        return null;
                    }else {
                        return result.fault("菜单创建成功，源码生成失败，请使用菜单中'重新生成源码'功能");
                    }
                }finally {
                    lock.unlock();
                }
            }
            if (downloadZip) {
                return null;
            }else {
                return result.success();
            }
        }catch (Exception e) {
            e.printStackTrace();
            if (downloadZip) {
                return null;
            }else {
                return result.fault("error:操作失败："+e.getLocalizedMessage());
            }
        }

    }

    /**
     * 预览，模板页面布局
     * @param keyRandom
     * @return
     */
    @GetMapping(value = "/getTemplateMap")
    @ResponseBody
    public Result getTemplateMap(String keyRandom) {
        if (StringUtils.isNull(keyRandom)) {
            return Result.getInstance().fault("No KeyRandom, 请检查模板配置是否正确");
        }
        freemarkerGen.initTemplateTable(keyRandom);
        Map<String, Object> map = freemarkerGen.getMap("");
        return Result.getInstance().setObj(map).success();
    }

    @GetMapping(value = "/buildCode4Enums")
    @ResponseBody
    public Result buildCode4Enums(String _userId, Long id) {
        Result result = new Result();
        try {
            lock.lock();
            mpGeneratorEnums.execute(id, _userId);
            return result.success();
        }catch (Exception e){
            e.printStackTrace();
            return result.fault("枚举源码生成失败");
        }finally {
            lock.unlock();
        }
    }




}
